package com.ruoyi.system.outto.goods.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttrTemplateMapper;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttributeMapper;
import com.ruoyi.system.V2.gameAttr.service.IGameAttributeService;
import com.ruoyi.system.V2.goodInfo.mapper.GoodsInfoImgMapper;
import com.ruoyi.system.V2.inter.mapper.ArtRecMapper;
import com.ruoyi.system.interAttr.domain.InterAttr;
import com.ruoyi.system.interAttr.mapper.InterAttrMapper;
import com.ruoyi.system.model.domain.GameAttrTemplate;
import com.ruoyi.system.model.domain.GameAttribute;
import com.ruoyi.system.model.domain.GoodsInfoImg;
import com.ruoyi.system.model.domain.SalePartner;
import com.ruoyi.system.model.dto.GoodsInfoAndAttrValueDto;
import com.ruoyi.system.outto.core.LCConstant;
import com.ruoyi.system.outto.dto.HttpUtil;
import com.ruoyi.system.outto.goods.NEW5173API;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author ruoyi
 * @data 2024/7/22
 * @apiNote
 */
@Slf4j
@Service
public class NEW5173APIImpl implements NEW5173API {
    @Resource
    private GoodsInfoImgMapper goodsInfoImgMapper;
    @Resource
    private IGameAttributeService gameAttributeService;
    @Resource
    private ArtRecMapper artRecMapper;
    @Resource
    private GameAttributeMapper gameAttributeMapper;
    @Resource
    private GameAttrTemplateMapper gameAttrTemplateMapper;
    @Resource
    InterAttrMapper interAttrMapper;


    static String URL = "http://gu.5173.com:9188/api/";

    @Override
    public AjaxResult addGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {

        JSONObject requestJson = new JSONObject();

        List<JSONObject> bathList = new ArrayList<>();
        JSONObject param = getParam(goodsInfoAndAttrValueDto, salePartner);
        bathList.add(param);
        requestJson.put("batch", bathList);
        Map<String, String> header = getHeader(salePartner.getSaleKey(),salePartner.getOther());
        HttpResponse execute = HttpRequest.post(URL + "batch")
                .header("Accept", "application/json, text/plain, */*")
                .header("Accept-Language", "zh-CN,zh;q=0.9")
                .header("Connection", "keep-alive")
                .header("Content-Type", "application/json;charset=UTF-8")
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like " +
                        "Gecko) Chrome / 122.0 .0 .0 Safari / 537.36 ")
                .header("Appid", header.get("Appid"))
                .header("CurTime", header.get("CurTime"))
                .header("Sign", header.get("Sign"))
                .body(requestJson.toJSONString()).execute();
        String response = execute.body();


        JSONObject body = JSONObject.parseObject(response);
        Map<String, Object> result = new HashMap<>();
        log.info("5173请求参数:" + requestJson.toJSONString());
        log.info("5173返回参数:" + response);

        if (body.getInteger("status") != 0) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
            JSONObject data = body.getJSONObject("data");
            List<String> stringList = JSONObject.parseArray(data.getString("items"), String.class);
            String outId = stringList.get(0);
            result.put("outId", outId);

            // 编辑 上架
            param = new JSONObject();
            param.put("docid", outId);
            param.put("status", 1);
            header = getHeader(salePartner.getSaleKey(),salePartner.getOther());
            String up = HttpRequest.post(URL + "account/edit")
                    .header("Accept", "application/json, text/plain, */*")
                    .header("Accept-Language", "zh-CN,zh;q=0.9")
                    .header("Connection", "keep-alive")
                    .header("Content-Type", "application/json;charset=UTF-8")
                    .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like " +
                            "Gecko) Chrome / 122.0 .0 .0 Safari / 537.36 ")
                    .header("Appid", header.get("Appid"))
                    .header("CurTime", header.get("CurTime"))
                    .header("Sign", header.get("Sign"))
                    .body(param.toJSONString()).execute().body();
            log.info("up 上架请求 "+param.toJSONString());
            log.info("up 上架 "+up);
        }
        result.put("msg", body.getString("msgs"));
        result.put("req", JSONObject.toJSONString(requestJson.toJSONString()));
        result.put("res", response);
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult editGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto,
                               SalePartner salePartner) {
        JSONObject param = getParam(goodsInfoAndAttrValueDto, salePartner);
        param.put("docid", goodsInfoAndAttrValueDto.getOutId());
        param.put("status", 1);
        // 编辑 上架
        Map<String, String> header = getHeader(salePartner.getSaleKey(),salePartner.getOther());
        HttpResponse execute = HttpRequest.post(URL + "account/edit")
                .header("Accept", "application/json, text/plain, */*")
                .header("Accept-Language", "zh-CN,zh;q=0.9")
                .header("Connection", "keep-alive")
                .header("Content-Type", "application/json;charset=UTF-8")
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like " +
                        "Gecko) Chrome / 122.0 .0 .0 Safari / 537.36 ")
                .header("Appid", header.get("Appid"))
                .header("CurTime", header.get("CurTime"))
                .header("Sign", header.get("Sign"))
                .body(param.toJSONString()).execute();
        String response = execute.body();
        log.info("5173编辑接口返回："+response);
        JSONObject body = JSONObject.parseObject(response);
        Map<String, Object> result = new HashMap<>();
        if (body.getInteger("status") != 0) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
        }
        result.put("req", param.toJSONString());
        result.put("res", response);
        result.put("msg", body.getString("msgs"));
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult delGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        Map<String, Object> result = new HashMap<>();

        JSONObject param = new JSONObject();
        param.put("docid", goodsInfoAndAttrValueDto.getOutId());
        param.put("status", 2);
        Map<String, String> header = getHeader(salePartner.getSaleKey(),salePartner.getOther());
        try {
            // 下架
            HttpResponse execute = HttpRequest.post(URL + "account/edit")
                    .header("Accept", "application/json, text/plain, */*")
                    .header("Accept-Language", "zh-CN,zh;q=0.9")
                    .header("Connection", "keep-alive")
                    .header("Content-Type", "application/json;charset=UTF-8")
                    .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like " +
                            "Gecko) Chrome / 122.0 .0 .0 Safari / 537.36 ")
                    .header("Appid", header.get("Appid"))
                    .header("CurTime", header.get("CurTime"))
                    .header("Sign", header.get("Sign"))
                    .body(param.toJSONString()).execute();
            String response = execute.body();
            log.info("5173编辑下架接口返回："+response);
            //删除
            param = new JSONObject();
            param.put("docid", goodsInfoAndAttrValueDto.getOutId());
            header = getDeleteHeader(salePartner.getSaleKey(),salePartner.getOther(),goodsInfoAndAttrValueDto.getOutId());
            execute = HttpRequest.post(URL + "account/delete")
                    .header("Accept", "application/json, text/plain, */*")
                    .header("Accept-Language", "zh-CN,zh;q=0.9")
                    .header("Connection", "keep-alive")
                    .header("Content-Type", "application/json;charset=UTF-8")
                    .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like " +
                            "Gecko) Chrome / 122.0 .0 .0 Safari / 537.36 ")
                    .header("Appid", header.get("Appid"))
                    .header("CurTime", header.get("CurTime"))
                    .header("Sign", header.get("Sign"))
                    .header("Sign", header.get("Sign"))
                    .body(param.toJSONString()).execute();
            response = execute.body();
            log.info("5173删除接口返回："+response);

            JSONObject body = JSONObject.parseObject(response);

            if (body.getInteger("status") == 0) {
                result.put("code", 200);
            } else {
                result.put("code", 500);
            }
            result.put("res", response);
            result.put("msg", body.getString("msgs"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success(result);
    }

    public JSONObject getParam(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        GameAttribute gameAttribute = null;
        if (goodsInfoAndAttrValueDto.getGameName().contains("王者荣耀")) {
            if(StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF16())){
                throw new GlobalException("实名不能为空!!!");
            }
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF16()));
        }
        else if (goodsInfoAndAttrValueDto.getGameName().contains("和平精英")) {
            if(StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF10())){
                throw new GlobalException("实名不能为空!!!");
            }
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF10()));
        }
        else if (goodsInfoAndAttrValueDto.getGameName().contains("原神")) {
            if(StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF20())){
                throw new GlobalException("实名不能为空!!!");
            }
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF20()));
        }
        else if (goodsInfoAndAttrValueDto.getGameName().contains("穿越火线")) {
            if(StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF3())){
                throw new GlobalException("实名不能为空!!!");
            }
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF3()));
        }
        else if (goodsInfoAndAttrValueDto.getGameName().equals("英雄联盟")) {
            if(StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF1())){
                throw new GlobalException("实名不能为空!!!");
            }
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF1()));
        }
        else if (goodsInfoAndAttrValueDto.getGameName().equals("英雄联盟(手游)")) {
            if(StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF4())){
                throw new GlobalException("实名不能为空!!!");
            }
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF4()));
        }
        else if (goodsInfoAndAttrValueDto.getGameName().contains("火影忍者")) {
            if(StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF7())){
                throw new GlobalException("实名不能为空!!!");
            }
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF7()));
        }
        else if (goodsInfoAndAttrValueDto.getGameName().contains("枪战王者")) {
            if(StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF10())){
                throw new GlobalException("实名不能为空!!!");
            }
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF10()));
        }
        else if (goodsInfoAndAttrValueDto.getGameName().contains("地下城与勇士")) {
            if(StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF1())){
                throw new GlobalException("实名不能为空!!!");
            }
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF1()));
        }
        else if (goodsInfoAndAttrValueDto.getGameName().contains("逆战")) {
            if(StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF1())){
                throw new GlobalException("实名不能为空!!!");
            }
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF1()));
        }
        else if (goodsInfoAndAttrValueDto.getGameName().contains("使命召唤手游")) {
            if(StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF3())){
                throw new GlobalException("实名不能为空!!!");
            }
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF3()));
        }
        else if(goodsInfoAndAttrValueDto.getGameName().contains("蛋仔派对")||goodsInfoAndAttrValueDto.getGameName().contains("光遇")||goodsInfoAndAttrValueDto.getGameName().contains("永劫无间")){

        } else if (goodsInfoAndAttrValueDto.getGameName().contains("无畏契约")) {
            if(StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF1())){
                throw new GlobalException("实名不能为空!!!");
            }
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF1()));
        } else if (goodsInfoAndAttrValueDto.getGameName().contains("QQ飞车端游")) {
            if(StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF1())){
                throw new GlobalException("实名不能为空!!!");
            }
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF1()));
        } else if (goodsInfoAndAttrValueDto.getGameName().contains("QQ飞车手游")) {
            if(StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF1())){
                throw new GlobalException("实名不能为空!!!");
            }
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF1()));
        } else if (goodsInfoAndAttrValueDto.getGameName().contains("金铲铲之战")) {
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF1()));
        } else if (goodsInfoAndAttrValueDto.getGameName().contains("暗区突围")) {
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF3()));
        } else if (goodsInfoAndAttrValueDto.getGameName().contains("三角洲行动")) {
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF7()));
        } else {
            throw new GlobalException("当前游戏暂不支持");
        }
        JSONObject action = new JSONObject();

        action.put("title", goodsInfoAndAttrValueDto.getDes());
        action.put("goods_desc", goodsInfoAndAttrValueDto.getDes());
        action.put("game_account", createQQAccount());
        action.put("price", goodsInfoAndAttrValueDto.getPrice());
        GoodsInfoImg goodsInfoImg = new GoodsInfoImg();
        goodsInfoImg.setGoodsId(goodsInfoAndAttrValueDto.getId());
        goodsInfoImg.setType(Constants.STR_1);
        List<GoodsInfoImg> infoImgs = goodsInfoImgMapper.selectGoodsInfoImgList(goodsInfoImg);
        String imgUrls = infoImgs.stream().map(info -> info.getImgUrl()).collect(Collectors.toList()).stream().collect(Collectors.joining(","));
        if (StringUtils.isNotEmpty(imgUrls)) {
            action.put("screenshot", imgUrls); //图片
        }else {
            action.put("screenshot", goodsInfoAndAttrValueDto.getTitleImg());
        }

        //自动匹配属性
        String substring = salePartner.getSaleName().substring(salePartner.getSaleName().indexOf("_")+1);
        InterAttr interAttr = interAttrMapper.selectInterAttrByConfig(substring, goodsInfoAndAttrValueDto.getGameId());
        action.put("game_id", interAttr.getInterGameId());
        action.put("game_name", interAttr.getInterGameName());

        //区服匹配
        builderServer(goodsInfoAndAttrValueDto, action, interAttr.getServer());

        if(goodsInfoAndAttrValueDto.getGameName().equals("王者荣耀")){
            String regiona = goodsInfoAndAttrValueDto.getSystemName()+goodsInfoAndAttrValueDto.getCarrierName();
            if(regiona.equals("安卓QQ")){
                action.put("area_id", 2080);
                action.put("area_name", "QQ(安卓)");
            }else if(regiona.equals("安卓微信")){
                action.put("area_id", 2081);
                action.put("area_name", "微信(安卓)");
            }else if(regiona.equals("苹果QQ")){
                action.put("area_id", 2082);
                action.put("area_name", "QQ(苹果)");
            }else {
                action.put("area_id", 2083);
                action.put("area_name", "微信(苹果)");
            }
            action.put("server_id", 24431);
            action.put("server_name", "全区全服");
        }
        else if(goodsInfoAndAttrValueDto.getGameName().equals("和平精英")){

            String regiona = goodsInfoAndAttrValueDto.getSystemName()+goodsInfoAndAttrValueDto.getCarrierName();
            if(regiona.equals("安卓QQ")){
                action.put("area_id", 243);
                action.put("area_name", "QQ(安卓)");
            }else if(regiona.equals("安卓微信")){
                action.put("area_id", 244);
                action.put("area_name", "微信(安卓)");
            }else if(regiona.equals("苹果QQ")){
                action.put("area_id", 245);
                action.put("area_name", "QQ(苹果)");
            }else {
                action.put("area_id", 246);
                action.put("area_name", "微信(苹果)");
            }
            action.put("server_id", 49037);
            action.put("server_name", "全区全服");

        }
        else if(goodsInfoAndAttrValueDto.getGameName().equals("枪战王者")){
            String regiona = goodsInfoAndAttrValueDto.getSystemName()+goodsInfoAndAttrValueDto.getCarrierName();
            if(regiona.equals("安卓QQ")){
                action.put("area_id", 2183);
                action.put("area_name", "QQ(安卓)");
            }else if(regiona.equals("安卓微信")){
                action.put("area_id", 2182);
                action.put("area_name", "微信(安卓)");
            }else if(regiona.equals("苹果QQ")){
                action.put("area_id", 2181);
                action.put("area_name", "QQ(苹果)");
            }else {
                action.put("area_id", 2180);
                action.put("area_name", "微信(苹果)");
            }
            action.put("server_id", 48201);
            action.put("server_name", "全区全服");
        }
        else if(goodsInfoAndAttrValueDto.getGameName().equals("穿越火线")){

            String area = "{\n" +
                    "            \"东部战区\": 205,\n" +
                    "            \"南部战区\": 206,\n" +
                    "            \"西部战区\": 207,\n" +
                    "            \"北部战区\": 208\n" +
                    "        }";

            JSONObject jsonObject1 = JSONObject.parseObject(area);

            String id = jsonObject1.getString(goodsInfoAndAttrValueDto.getGroupName());

            action.put("area_id", id);
            action.put("area_name", goodsInfoAndAttrValueDto.getGroupName());

//            if(goodsInfoAndAttrValueDto.getGroupName().contains("东部战区")){
//                action.put("area_id", 205);
//                action.put("area_name", "电信区");
//            }else {
//                action.put("area_id", 207);
//                action.put("area_name", "网通区");
//            }
            String server = "{\"安徽一区\":2211,\"福建一区\":2212,\"广东一区\":2213,\"广东二区\":2214,\"广东三区\":2215,\"广东四区\":2216,\"广西一区\":2217,\"湖北一区\":2218,\"湖北二区\":2219,\"湖南一区\":2220,\"湖南二区\":2221,\"江苏一区\":2222,\"江苏二区\":2223,\"江西一区\":2224,\"南方大区\":2225,\"陕西一区\":2226,\"上海一区\":2227,\"上海二区\":2228,\"四川一区\":2229,\"四川二区\":2230,\"云南一区\":2231,\"浙江一区\":2232,\"浙江二区\":2233,\"重庆一区\":2234,\"体验服\":2235,\"北方大区\":2236,\"北京一区\":2237,\"北京二区\":2238,\"北京三区\":2239,\"北京四区\":2240,\"河北一区\":2241,\"河南一区\":2242,\"河南二区\":2243,\"黑龙江区\":2244,\"吉林一区\":2245,\"辽宁一区\":2246,\"辽宁二区\":2247,\"辽宁三区\":2248,\"山东一区\":2249,\"山东二区\":2250,\"山西一区\":2251,\"教育网专区\":2252,\"移动专区\":2253,\"高清竞技大区\":2254}\n";
            JSONObject jsonObject = JSONObject.parseObject(server);
            jsonObject.keySet().forEach(key -> {
                Object value = jsonObject.get(key);
                if(goodsInfoAndAttrValueDto.getServerName().equals(key)){
                    action.put("server_id", Integer.parseInt(value.toString()));
                    action.put("server_name", key);
                }
            });
        }
        else if(goodsInfoAndAttrValueDto.getGameName().equals("英雄联盟")){
            if(goodsInfoAndAttrValueDto.getGroupName().contains("电信")){
                action.put("area_id", 415);
                action.put("area_name", "电信");
            }else {
                action.put("area_id", 416);
                action.put("area_name", "网通");
            }
            String server = "{\"艾欧尼亚\":5702,\"暗影岛\":5703,\"班德尔城\":5704,\"裁决之地\":5705,\"钢铁烈阳\":5706,\"黑色玫瑰\":5707,\"教育网专区\":5708,\"巨神峰\":5709,\"均衡教派\":5710,\"卡拉曼达\":5711,\"雷瑟守备\":5712,\"诺克萨斯\":5713,\"皮城警备\":5714,\"皮尔特沃夫\":5715,\"守望之海\":5716,\"水晶之痕\":5717,\"影流\":5718,\"战争学院\":5719,\"征服之海\":5720,\"祖安\":5721,\"比尔吉沃特\":5722,\"德玛西亚\":5723,\"弗雷尔卓德\":5724,\"无畏先锋\":5725,\"恕瑞玛\":5726,\"扭曲丛林\":5727,\"巨龙之巢\":5728,\"试练之地\":5729,\"男爵领域\":5730,\"峡谷之巅\":5731}\n";
            JSONObject jsonObject = JSONObject.parseObject(server);
            jsonObject.keySet().forEach(key -> {
                Object value = jsonObject.get(key);
                if(goodsInfoAndAttrValueDto.getServerName().equals(key)){
                    action.put("server_id", Integer.parseInt(value.toString()));
                    action.put("server_name", key);
                }
            });
        }
        else if(goodsInfoAndAttrValueDto.getGameName().equals("火影忍者")){
            action.put("area_id", 1711);
            action.put("area_name", "普通区");
            action.put("server_id", 19698);
            action.put("server_name", "1区");
        }
        else if(goodsInfoAndAttrValueDto.getGameName().equals("原神")){
            if(goodsInfoAndAttrValueDto.getCarrierName().equals("哔哩哔哩")) {
                action.put("area_id", 2072);
                action.put("area_name", "哔哩哔哩(安卓)");
            }else {
                action.put("area_id", 2073);
                action.put("area_name", "米哈游(安卓)");
            }
            action.put("server_id", 23230);
            action.put("server_name", "全区全服");
        }
        else if(goodsInfoAndAttrValueDto.getGameName().equals("金铲铲之战")){
            String regiona = goodsInfoAndAttrValueDto.getSystemName()+goodsInfoAndAttrValueDto.getCarrierName();
            if(regiona.equals("安卓QQ")){
                action.put("area_id", 2250);
                action.put("area_name", "QQ(安卓)");
            }else if(regiona.equals("安卓微信")){
                action.put("area_id", 2251);
                action.put("area_name", "微信(安卓)");
            }else if(regiona.equals("苹果QQ")){
                action.put("area_id", 2252);
                action.put("area_name", "QQ(苹果)");
            }else {
                action.put("area_id", 2253);
                action.put("area_name", "微信(苹果)");
            }
            action.put("server_id", 52163);
            action.put("server_name", "全区全服");
        }
        else if(goodsInfoAndAttrValueDto.getGameName().equals("永劫无间")){
            action.put("server_id", 5632);
            action.put("server_name", "全区全服");
            if(goodsInfoAndAttrValueDto.getServerName().contains("手机")){
                action.put("30220", "手机账号");
            }else {
                action.put("30220", "邮箱账号");
            }
        }
        else if(goodsInfoAndAttrValueDto.getGameName().equals("暗区突围")){
            action.put("server_id", 49041);
            action.put("server_name", "全区全服");
        }
        else if(goodsInfoAndAttrValueDto.getGameName().equals("英雄联盟(手游)")){
            action.put("server_id", 49204);
            action.put("server_name", "全区全服");
        }
        else if(goodsInfoAndAttrValueDto.getGameName().equals("使命召唤手游")){
            action.put("server_id", 52167);
            action.put("server_name", "全区全服");
        }
        else if(goodsInfoAndAttrValueDto.getGameName().equals("三角洲行动")){
            if(goodsInfoAndAttrValueDto.getCarrierName().equals("QQ")){
                action.put("area_id", 3765);
                action.put("area_name", "QQ");
            }else {
                action.put("area_id", 3766);
                action.put("area_name", "微信");
            }
            action.put("server_id", 62244);
            action.put("server_name", "全区全服");
        }
        action.put("career", "无");
        action.put("level", "0");
        action.put("credit", "0");
        action.put("goods_num", "1");
        action.put("goods_source", "1");
//
//
        if(goodsInfoAndAttrValueDto.getGameName().equals("永劫无间")){
            action.put("is_real", 1);//是否实名 1是，2否
            action.put("is_face", 1);//是否实名 1是，2否
        }else {
            if (gameAttribute.getFieldName().equals("可二次实名") || gameAttribute.getFieldName().equals("有修改人脸机会/实名是本人")
                    || gameAttribute.getFieldName().equals("有修改机会且实名是本人") || gameAttribute.getFieldName().equals("可修改实名")
                    || gameAttribute.getFieldName().equals("可改二次") || gameAttribute.getFieldName().equals("可实名")) {
                action.put("is_real", 1);//是否实名 1是，2否
                action.put("is_face", 1);//是否实名 1是，2否
            } else {
                action.put("is_real", 2);//是否实名 1是，2否
                action.put("is_face", 2);//是否实名 1是，2否
            }
        }

        JSONArray extendAttrs = new JSONArray();
        //开始匹配单选属性
        builderRadioAttr(goodsInfoAndAttrValueDto, interAttr.getRadioAttr(),extendAttrs);
        //开始匹配多选属性
        builderCheckAttr(goodsInfoAndAttrValueDto, interAttr.getCheckAttr(),extendAttrs);
        //开始匹配输入框属性
        builderInputAttr(goodsInfoAndAttrValueDto, interAttr.getInputAttr(),extendAttrs);
        action.put("extendAttrs", extendAttrs);
        return action;
    }

    private void builderInputAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, String inputAttr,JSONArray extendAttrs) {
//        JSONArray propertys = Objects.isNull(params.get("property")) ? new JSONArray() : JSONArray.parseArray(params.get("property").toString());
        Field[] declaredFields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();

        //========================开始匹配输入框=====================//
        JSONObject jsonObject1 = JSONObject.parseObject(inputAttr);
        String inputJson = jsonObject1.getString("inputJson");
        List<JSONObject> jsonObjects1 = JSONObject.parseArray(inputJson, JSONObject.class);
        GameAttrTemplate gameAttrTemplate = new GameAttrTemplate();
        gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
        gameAttrTemplate.setIsEnable("0");
        ArrayList types = new ArrayList<>();
        types.add("number");
        types.add("input");
        gameAttrTemplate.setFieldTypes(types);
        List<GameAttrTemplate> inputTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);
        List<JSONObject> defInputObjects = new ArrayList<>();
        defInputObjects.addAll(jsonObjects1);
        Map<String,Object> map = new HashMap<>();
        for (JSONObject object : jsonObjects1) {
            map = new HashMap<>();
            for (GameAttrTemplate inputTemplate : inputTemplates) {
                String aavName = inputTemplate.getAavName();
                if (Objects.equals(object.getString("aavName"), inputTemplate.getAavName())) {
                    defInputObjects.remove(object);
                    Integer interId = object.getInteger("interId");
                    for (Field declaredField : declaredFields) {
                        String name = declaredField.getName();
                        if (Objects.equals(aavName, name)) {
                            declaredField.setAccessible(true);
                            Object o = null;
                            try {
                                o = declaredField.get(goodsInfoAndAttrValueDto);
                            } catch (IllegalAccessException e) {
                                throw new GlobalException("3属性参数错误，请匹配后重新配置");
                            }
                            String oneValue = String.valueOf(o);
                            if (StringUtils.isNotEmpty(oneValue)) {
                                map.put("eid", interId);
                                map.put("evs", oneValue);
                                extendAttrs.add(map);
                            }
                        }
                    }
                }
            }
        }
        //开始匹配默认值
        for (JSONObject object : defInputObjects) {
            map = new HashMap<>();
            Integer defaultValue = object.getInteger("defaultValue");
            if (Objects.nonNull(defaultValue)) {
                map.put("eid", defaultValue);
                map.put("evs", "0");
                extendAttrs.add(map);
            }
        }

    }

    private void builderCheckAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, String checkAttr, JSONArray extendAttrs) {
        /**
         * 1、先查询自定义中所有多选的字段
         * 2、再查该账号单选字段中的选项
         * 3、再去接口属性匹配表过滤
         */
        Field[] declaredFields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();
        JSONObject checkAttrJson = JSONObject.parseObject(checkAttr);
        String interCheckBoxReqs = checkAttrJson.getString("interCheckBoxReqs");
        List<JSONObject> checkJsonList = JSONObject.parseArray(interCheckBoxReqs, JSONObject.class);
        if (org.springframework.util.CollectionUtils.isEmpty(checkAttrJson)) {
            throw new GlobalException("接口多选属性暂未配置");
        }

        GameAttrTemplate gameAttrTemplate = new GameAttrTemplate();
        gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
        gameAttrTemplate.setIsEnable("0");
        List<String> types = new ArrayList<>();
        types.add("checkbox");
        types.add("boxradio");
        gameAttrTemplate.setFieldTypes(types);
        List<GameAttrTemplate> checkAttrTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);
        Map<String,Object> map = new HashMap<>();
        for (JSONObject object : checkJsonList) {
            for (GameAttrTemplate attrTemplate : checkAttrTemplates) {

                String aavName = attrTemplate.getAavName();
                for (Field declaredField : declaredFields) {
                    String name = declaredField.getName();
                    if (aavName.equals(name)) {
                        declaredField.setAccessible(true);
                        Object o = null;
                        try {
                            o = declaredField.get(goodsInfoAndAttrValueDto);
                        } catch (IllegalAccessException e) {
                            throw new GlobalException("多选项" + attrTemplate.getFieldName() + "匹配错误");
                        }
                        String oneValue = String.valueOf(o);
                        String interCheckBoxReqsStr = object.getString("interCheckBoxReqs");
                        //开始匹配二级属性
                        List<JSONObject> jsonObjects2 = JSONObject.parseArray(interCheckBoxReqsStr, JSONObject.class);
                        /**
                         * 咱们的f字段  多选项都是用空格 隔开，用,号切割数组，跟匹配的数据匹配、匹配上说明此账号勾选的有此属性
                         */
                        for (JSONObject jsonObject1 : jsonObjects2) {
                            String[] split1 = oneValue.split(",");
                            String ydConfigId1 = jsonObject1.getString("YdConfigId");
                            if(StringUtils.isNotEmpty(ydConfigId1)) {
                                ydConfigId1 = ydConfigId1.replace(" ", "");
                                for (String s : split1) {
                                    if (Objects.equals(s, ydConfigId1)) {
                                        String InterConfigId2 = jsonObject1.getString("InterConfigId");
                                        map = new HashMap<>();
                                        map.put("eid", object.getInteger("id"));
                                        map.put("evs", InterConfigId2);
                                        if(Objects.nonNull(map.get("evs"))){
                                            extendAttrs.add(map);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    private void builderRadioAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, String radioAttr, JSONArray extendAttrs) {
        //========================开始匹配单选属性=====================//
        JSONObject jsonObject = JSONObject.parseObject(radioAttr);
        String interRadioReqs = jsonObject.getString("interRadioReqs");
        log.info(JSONObject.toJSONString(interRadioReqs));
        List<JSONObject> jsonObjects = JSONObject.parseArray(interRadioReqs, JSONObject.class);
        if (!org.springframework.util.CollectionUtils.isEmpty(jsonObjects)) {
            /**
             * 1、先查询自定义中所有单选的字段
             * 2、再查该账号单选字段中的选项
             * 3、再去接口属性匹配表过滤
             */
            GameAttrTemplate gameAttrTemplate = new GameAttrTemplate();
            gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
            gameAttrTemplate.setIsEnable("0");
            gameAttrTemplate.setFieldType("radio");
            List<GameAttrTemplate> gameAttrTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);
            Field[] declaredFields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();


            List<JSONObject> defObjects = new ArrayList<>();
            defObjects.addAll(jsonObjects);


            //属性 不参与加密
            Map<String,Object> map = new HashMap<>();

            for (JSONObject object : jsonObjects) {
                map = new HashMap<>();
                for (GameAttrTemplate attrTemplate : gameAttrTemplates) {
                    String aavName = attrTemplate.getAavName();
                    for (Field declaredField : declaredFields) {
                        String name = declaredField.getName();
                        if (aavName.equals(name)) {
                            //一级属性
                            //注意 YdConfigId 对应的是 f字段对应的 id
                            if (Objects.equals(object.getLong("YdConfigId"), attrTemplate.getId())) {
                                Integer InterConfigId = object.getInteger("InterConfigId");
                                defObjects.remove(object);//如果匹配上，则去掉
                                String interRadioReqs1 = object.getString("interRadioReqs");
                                List<JSONObject> jsonObjects2 = JSONObject.parseArray(interRadioReqs1, JSONObject.class);
                                declaredField.setAccessible(true);
                                try {
                                    //获取选择的值 例如  实名中的可二次
                                    Object o = declaredField.get(goodsInfoAndAttrValueDto);
                                    String oneValue = String.valueOf(o);
                                    List<JSONObject> twoAttr = jsonObjects2.stream().filter(j -> Objects.equals(j.getString("YdConfigId"), oneValue)).collect(Collectors.toList());
                                    String interConfigName = object.getString("InterConfigName");
                                    String defaultValue = object.getString("defaultValue");
                                    if (!org.springframework.util.CollectionUtils.isEmpty(twoAttr)) {
                                        JSONObject jsonObject2 = twoAttr.get(0);
                                        String interConfigId2 = jsonObject2.getString("InterConfigId");
                                        map.put("eid", InterConfigId);
                                        map.put("evs", interConfigId2);
                                        if(Objects.nonNull(map.get("evs"))){
                                            extendAttrs.add(map);
                                        }
                                    }
                                } catch (Exception e) {
                                    throw new GlobalException("单选项" + attrTemplate.getFieldName() + "匹配错误");
                                }
                            }
                        }
                    }
                }
            }
            //开始匹配默认值
            for (JSONObject object : defObjects) {
                map = new HashMap<>();
                interRadioReqs = object.getString("interRadioReqs");
                jsonObjects = JSONObject.parseArray(interRadioReqs, JSONObject.class);
                for (JSONObject objects : jsonObjects) {
                    if(StringUtils.isNotEmpty(objects.getString("defaultValue"))){
                        map.put("eid", object.getInteger("id"));
                        map.put("evs", objects.getString("name"));
                        extendAttrs.add(map);
                    }
                }
            }
            //========================单选属性匹配结束=====================//
        }
    }

    private void builderServer(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, Map action, String server) {
        //========================开始匹配区服属性=====================//
        JSONObject jsonObject = JSONObject.parseObject(server);
        //开始匹配一级区服
        String interServeReqs = jsonObject.getString("interServeReqs");
        String qufuid = "";
        JSONObject oneServerJson = new JSONObject();
        List<JSONObject> oneServer = JSONObject.parseArray(interServeReqs, JSONObject.class);
         if (Objects.equals(goodsInfoAndAttrValueDto.getGameType(), "0")) {
            qufuid = goodsInfoAndAttrValueDto.getSystemId()+"";
            for (JSONObject object : oneServer) {
                String ydServeId = object.getString("YdServeId");
                if (StringUtils.isNotEmpty(ydServeId)) {
                    ydServeId = ydServeId.replace(",", "").replace(" ", "");
                    if (ydServeId.contains(qufuid)) {
                        String interServerRes = object.getString("interServerRes");
                        List<JSONObject> twoServer = JSONObject.parseArray(interServerRes, JSONObject.class);
                        for(JSONObject object2 : twoServer) {
                            String ydServeId2 = object2.getString("YdServeId");
                            if(StringUtils.isNotEmpty(ydServeId2)) {
                                ydServeId2 = ydServeId2.replace(",", "").replace(" ", "");
                                qufuid = goodsInfoAndAttrValueDto.getSystemId() + "" + goodsInfoAndAttrValueDto.getCarrierId() + "";
                                if (ydServeId2.contains(qufuid)) {
                                    System.out.println(ydServeId2 + "======" + qufuid);
                                    action.put("area_id", object2.getInteger("id"));
                                    action.put("area_name", object2.getString("name"));
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }else if(Objects.equals(goodsInfoAndAttrValueDto.getGameName(), "永劫无间")) {
            qufuid = goodsInfoAndAttrValueDto.getGroupId()+"";
            for (JSONObject object : oneServer) {
                String ydServeId = object.getString("YdServeId");
                if (StringUtils.isNotEmpty(ydServeId)) {
                    ydServeId = ydServeId.replace(",", "").replace(" ", "");
                    if (ydServeId.contains(qufuid)) {
                        String interServerRes = object.getString("interServerRes");
                        List<JSONObject> twoServer = JSONObject.parseArray(interServerRes, JSONObject.class);
                        for(JSONObject object2 : twoServer) {
                            String ydServeId2 = object2.getString("YdServeId");
                            ydServeId2 = ydServeId2.replace(",", "").replace(" ", "");
                            if(ydServeId2.equals(qufuid)) {
                                action.put("area_id", object2.getInteger("id"));
                                action.put("area_name", object2.getString("name"));
                                break;
                            }
                        }
                    }
                }
            }
        }else if(!Objects.equals(goodsInfoAndAttrValueDto.getGameName(), "英雄联盟")){
            qufuid = goodsInfoAndAttrValueDto.getServerId() + "";
            for (JSONObject object : oneServer) {
                String interServeReqs1 = object.getString("interServerRes");
                if(StringUtils.isNotEmpty(interServeReqs1)) {
                    List<JSONObject> oneServers = JSONObject.parseArray(interServeReqs1, JSONObject.class);
                    for (JSONObject jsonObject1 : oneServers) {
                        String ydServeId = jsonObject1.getString("YdServeId");
                        if(StringUtils.isNotEmpty(ydServeId)) {
                            ydServeId = ydServeId.replace(",", "").replace(" ", "");
                            if (qufuid.contains(ydServeId)) {
                                action.put("area_id", object.getInteger("id"));
                                action.put("area_name", object.getString("name"));
                                break;
                            }
                        }
                    }
                }
            }
        }
    }

    public static Map<String, String> getHeader(String appId, String appSecret) {

        String curTime = String.valueOf(Instant.now().getEpochSecond());

        Map<String, String> params = new HashMap<>();
        params.put("Appid", appId);
        params.put("CurTime", curTime);

        List<String> keys = new ArrayList<>(params.keySet());
        Collections.sort(keys);

        StringBuilder signMessage = new StringBuilder();
        for (String key : keys) {
            try {
                if (signMessage.length() > 0) {
                    signMessage.append("&");
                }
                signMessage.append(URLEncoder.encode(key, "UTF-8"))
                        .append("=")
                        .append(URLEncoder.encode(params.get(key), "UTF-8"));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        String sign = generateSignature(signMessage.toString(), appSecret);
        params.put("Sign", sign);
        return params;
    }
    public static Map<String, String> getDeleteHeader(String appId, String appSecret,String docid) {

        String curTime = String.valueOf(Instant.now().getEpochSecond());

        Map<String, String> params = new HashMap<>();
        params.put("Appid", appId);
        params.put("CurTime", curTime);
        params.put("docid", docid);

        List<String> keys = new ArrayList<>(params.keySet());
        Collections.sort(keys);

        StringBuilder signMessage = new StringBuilder();
        for (String key : keys) {
            try {
                if (signMessage.length() > 0) {
                    signMessage.append("&");
                }
                signMessage.append(URLEncoder.encode(key, "UTF-8"))
                        .append("=")
                        .append(URLEncoder.encode(params.get(key), "UTF-8"));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        String sign = generateSignature(signMessage.toString(), appSecret);
        params.put("Sign", sign);
        return params;
    }
    public static String generateSignature(String message, String secretKey) {
        try {
            Mac sha256Hmac = Mac.getInstance("HmacSHA256");
            SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
            sha256Hmac.init(secretKeySpec);
            byte[] hash = sha256Hmac.doFinal(message.getBytes(StandardCharsets.UTF_8));
            return bytesToHex(hash);
        } catch (Exception e) {
            throw new RuntimeException("Failed to generate HMAC : " + e.getMessage());
        }
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (byte b : bytes) {
            result.append(String.format("%02x", b));
        }
        return result.toString();
    }

    public static void main(String[] args) {
        String games = getAtta(43);
        System.out.println(games);
    }

    static String getAtta(Integer gameId){
        String url = "http://gu.5173.com:9188/api/game/getGameAccountData?game_id="+gameId;
        Map<String, String> header = getHeader("14wBcgvIVi19wrN82n9k0mrb", "mESZJKc6Zlx9aoxW");
        Map<String, String> action = new HashMap<>();
        String response = HttpUtil.doGet(url, action, header);
        return response;
    }

    static String getArea(Integer gameId){
        String url = "http://gu.5173.com:9188/api/game/dict?game_id="+gameId;
        Map<String, String> header = getHeader("14wBcgvIVi19wrN82n9k0mrb", "mESZJKc6Zlx9aoxW");
        Map<String, String> action = new HashMap<>();
        String response = HttpUtil.doGet(url, action, header);
        return response;
    }

    static String getGames(){
        String url = "http://gu.5173.com:9188/api/games?page=1&page_size=9999";
        Map<String, String> header = getHeader("14wBcgvIVi19wrN82n9k0mrb", "mESZJKc6Zlx9aoxW");
        Map<String, String> action = new HashMap<>();
        String response = HttpUtil.doGet(url, action, header);
        return response;
    }

    public static String createQQAccount() {
        int num = 8;
        String[] vec = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
        num = num <= 0 ? 1 : num;
        StringBuffer str = new StringBuffer(10);
        for (int i = 0; i < num; i++) {
            int r1 = Long.valueOf(Math.round(Math.random() * (vec.length - 1))).intValue();
            str.append(vec[r1]);
        }
        return str.toString();
    }
}
